package com.njupt.towerssystem.services.impl;

import com.njupt.towerssystem.domain.Managers;
import com.njupt.towerssystem.services.LoginManagerService;
import org.springframework.context.annotation.Scope;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.Duration;
import java.util.UUID;

@Service
@Scope("prototype") //原型模型（每次请求都会创建一个新的bean实例）
public class LoginManagerServiceImpl implements LoginManagerService {
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    public  Managers tokenManagers(String res,String token){
        String[] infos=res.toString().split(",");
        Managers ms=Managers.builder()
                .username(infos[0])
                .loginname(infos[1])
                .loginpwd(infos[2])
                .tel(infos[3])
                .department(infos[4])
                .token(token)
                .build();
        return ms;
    }
    @Override
    public Managers login(String loginname, String loginpwd, String token) {
        if(loginname!=null){
            String res = stringRedisTemplate.opsForHash().get("managers",loginname+","+loginpwd).toString();
            //找到对应用户
            if(res!=null){
                //生成唯一令牌
                String tk=UUID.randomUUID().toString().replaceAll("-","");
                //将令牌存放到redis数据库中,让令牌存放30秒
                stringRedisTemplate.opsForValue().set(tk,loginname+","+loginpwd, Duration.ofSeconds(30));
                return tokenManagers(res,tk);
            }else{
                return null;
            }
        }else{
            //验证用户传入的token,查看是否存在
            String s_key=stringRedisTemplate.opsForValue().get(token);
            if(s_key!=null){
                String res = stringRedisTemplate.opsForHash().get("managers", s_key).toString();
                return tokenManagers(res,token);
            }

            }
        return null;
    }

}

